<?php
namespace Foxframe;

class Service
{
	protected $em;

	public function __construct()
	{
		$this->em	= \Foxframe\Registry::get('entityManager');
	}

	public function save(array $data, $className)
	{
		$entity					= new $className;
		$metaData				= $this->em->getClassMetadata(get_class($entity));
		$identifier				= $metaData->getSingleIdentifierFieldName();
		$associationMappings	= $metaData->getAssociationMappings();
		foreach ($data as $key => $value)
		{
			if (key_exists($key, $associationMappings))
			{
				$targetEntity	= $associationMappings[$key]['targetEntity'];
				$class	= $this->em->find($targetEntity,$value);
				$data[$key]	= $class;
			}
		}

		if (isset($data[$identifier]) && !empty($data[$identifier]))
			$entity	= $this->em->find($className, $data[$identifier]);

		\Foxframe\Configurator::configure($entity, $data);
		$this->em->persist($entity);
		return $entity;
	}

	public function delete($primaryKey, $className)
	{
		$entity	= $this->em->find($className, $primaryKey);
		$this->em->remove($entity);
	}
}